package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.service.DishService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("dish")
public class DishController {
    @Autowired
    DishService dishService;
    @Autowired
    RedisTemplate<Object,Object> redisTemplate;
    @PostMapping          //由于前端传输过来的数组涉及二个表 单个实体类会丢失数据 所以创建DTO 接收数据
     public R<String> saveFlavor(@RequestBody DishDto dishDto){
        dishService.saveFlavor(dishDto);
        //添加菜品时要删除缓存 不然客户端查到的还是缓存的之前的数据
        String key="dish:"+dishDto.getCategoryId()+"null";
        redisTemplate.delete(key);
        return  R.success("添加成功");
    }
    /**
     * 分页查询
     */
    @GetMapping("page")
    public R<Page<DishDto>> pageDishDto(Integer page,Integer pageSize,String name){
        Page<DishDto> pageInfo= dishService.pageDishDto(page,pageSize,name);
        return R.success(pageInfo);
    }
    /**
     * 根据ID查询数据回显
     */
    @GetMapping("{id}")
    public R<DishDto> updateFlavor(@PathVariable Long id){
        DishDto dishDto=dishService.updateFlavor(id);
        return R.success(dishDto);
    }
    /**
     * 修改
     */
    @PutMapping
    public R<String> updateDishById(@RequestBody DishDto dishDto){
        dishService.updateDishById(dishDto);
        return R.success("修改成功");
    }
    /**
     * 批量启售/禁售
     */
    @PostMapping("status/{status}")
    public R<String> updateByIds(@PathVariable Integer status,Long[] ids ){
        dishService.update()
                .in("id",ids)
                .set("status",status)
                .update();
        return R.success("ok");
    }

    /**
     * 查询菜品的详情信息
     * @param categoryId
     * @param name
     * @return
     */
    @GetMapping("list")

    public R<List<DishDto>> list(Long categoryId,String name){
        //先从redis中获取数据
        List<DishDto> dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get("dish:" + categoryId+name);
        if (dishDtoList!=null) {
            return R.success(dishDtoList);
        }
        List<DishDto> list=dishService.listDishDto(categoryId,name);
        //把查询到的数据存到redis中
        redisTemplate.opsForValue().set("dish:" + categoryId+name,list,5, TimeUnit.HOURS);
        return R.success(list);
    }
    /**
     * 菜品批量删除
     */
    @DeleteMapping
    public R<String> deleteDish(Long [] ids){
        dishService.deleteDish(ids);
        return R.success("删除成功");
    }
}
